package org.budo.launcher.service;

import java.net.URL;
import java.util.Properties;

import org.budo.launcher.service.util.LauncherUtil;
import org.budo.support.java.net.util.JavaNetUrlUtil;
import org.budo.support.lang.util.PropertiesUtil;
import org.budo.support.lang.util.SystemUtil;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @author lmw
 */
public abstract class AbstractBudoLauncherService implements BudoLauncherService {
    private static final Logger log = Slf4j.getLogger();

    private static final Integer DEFAULT_PORT = 8080;

    protected static final String[] DEFAULT_WELCOME_FILES = { "index.jsp", "index.htm" };

    protected Integer getLauncherPort() {
        Integer budoPort = LauncherUtil.getPort();
        if (null != budoPort) {
            return budoPort;
        }

        return DEFAULT_PORT;
    }

    // -Djetty.port=8080
    protected Integer getLauncherPort(String portKey) {
        Integer jettyPort = SystemUtil.getInteger(portKey);
        if (null != jettyPort) {
            return jettyPort;
        }

        return this.getLauncherPort();
    }

    protected String getContextPath() {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL url = classLoader.getResource("automan.conf");
        if (null == url) {
            log.warn("#83 automan.conf not found by classLoader, " + classLoader);
            return "/";
        }

        Properties properties = PropertiesUtil.load(JavaNetUrlUtil.openStream(url));
        String contextPath = properties.getProperty("automan.CONTEXT_PATH", "/");

        if (!contextPath.startsWith("/")) {
            log.warn("#54 contextPath should startsWith /, contextPath=" + contextPath);
            return "/" + contextPath;
        }

        return contextPath;
    }
}